package com.zhc.dejingapi.utils.downqing;

//import com.alibaba.fastjson.JSON;

import com.google.gson.Gson;
import com.zhc.dejingapi.pojo.qingflow.QingflowApiInfo;
import com.zhc.dejingapi.pojo.qingflow.downdata.*;
import com.zhc.dejingapi.utils.qing.QingflowAPIUtils;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class QingDownDataUtils {
    private String appKey;
    public  QingDownDataUtils(String strAppKey, JdbcTemplate mySqlJdbc, QingflowApiInfo qqingflowApiInfo1){
        appKey=strAppKey;
        mySqlJdbcTemplate=mySqlJdbc;
        mainDBModel=new QingDownDataMainDBModel(strAppKey,mySqlJdbc);
        mainDBModel.loadDetailItems(mySqlJdbc);
        mainDBModel.loadMainFields(mySqlJdbc);
        qqingflowApiInfo=qqingflowApiInfo1;

    }

    @Getter
    private QingflowApiInfo qqingflowApiInfo;
    @Getter
    private QingDownDataMainDBModel mainDBModel;

    @Getter
    private JdbcTemplate mySqlJdbcTemplate;
    public boolean getAppDownData( String downBatchId, String  qingFieldTitle, String minDate,String maxDate){

        String strSql="SELECT b.queId\n" +
                "from qing_appinfo a\n" +
                "LEFT JOIN qing_appfields b on a.main_id=b.appMain_Id\n" +
                "where a.appKey=? and b.queTitle=? ";
        Long lQueId=mySqlJdbcTemplate.queryForObject(strSql,Long.class,appKey,qingFieldTitle);
        return getAppDownData(downBatchId,lQueId,minDate,maxDate);
    }

    public boolean getAppDownData(String downBatchId, long  queId, String minDate,String maxDate){
        boolean bSuccess=false;
        DownDataPostMainModel mainPostModel=new DownDataPostMainModel()    ;
        DownDataPostQueryModel queryModel=new DownDataPostQueryModel();
        queryModel.setQueId(queId);
        queryModel.setMinValue(minDate);
        queryModel.setMaxValue(maxDate);
        queryModel.setScope(1);//筛选数据范围， 1：全部，2：已填写，3：未填写
        mainPostModel.setPageNum(1);
        mainPostModel.setPageSize(200);//轻流无法超过200行的数据
        List<DownDataPostQueryModel> listQueryModel = new ArrayList<>();
        listQueryModel.add(queryModel);
        mainPostModel.setQueries(listQueryModel);
        //String strBody= JSON.toJSONString(mainPostModel);
        Gson gson=new Gson();
        String strBody=gson.toJson(mainPostModel);

        try {

            QingDownDataResultMainBase fieldResultMainBase = QingflowAPIUtils.GetAppDataInfo(qqingflowApiInfo, appKey, strBody);

            if (fieldResultMainBase == null
                    || fieldResultMainBase.getResult() == null
                    || fieldResultMainBase.getResult().getResult() == null) {

            } else {
                if (fieldResultMainBase.getErrCode() == 0) {

                    QingDownDataResultDetailBase resultDetailBase = fieldResultMainBase.getResult();
                    if (resultDetailBase.getResult().isEmpty()) {

                    } else {

                        DealAppDownData(downBatchId,resultDetailBase.getResult());
                        if (resultDetailBase.getResultAmount()>200){
                            int iPageNum=resultDetailBase.getResultAmount()/200;
                            if(resultDetailBase.getResultAmount()%200==0){

                            }
                            else{
                                iPageNum++;
                            }
                            //第一页已经获取了。
                            int iNowPage=2;
                            while (iNowPage<=iPageNum){
                                mainPostModel.setPageNum(iNowPage);
                                //strBody= JSON.toJSONString(mainPostModel);
                                strBody=gson.toJson(mainPostModel);
                                try{

                                    fieldResultMainBase = QingflowAPIUtils.GetAppDataInfo(qqingflowApiInfo, appKey, strBody);
                                    if (fieldResultMainBase.getErrCode() == 0){
                                        resultDetailBase = fieldResultMainBase.getResult();
                                        if (resultDetailBase.getResult().isEmpty()) {

                                        }
                                        else{
                                            DealAppDownData(downBatchId,resultDetailBase.getResult());
                                        }
                                    }
                                }
                                catch (Exception e){

                                }
                                iNowPage++;
                            }

                        }

                    }
                } else {
                    log.error(fieldResultMainBase.getErrCode() + "\n" + fieldResultMainBase.getErrMsg());
                }
            }

            String strSql="Update qing_downdatabatch set isValid=0 where appKey=?";
            mySqlJdbcTemplate.update(strSql,appKey);
            strSql="Update qing_downdatabatch set isValid=1 where appKey=? and downBatchId=?";
            mySqlJdbcTemplate.update(strSql,appKey,downBatchId);

            //找到最近的三第记录

            //region 删除多余的历史记录
            strSql="SELECT downBatchId \n" +
                    "from qing_downdatabatch \n" +
                    "where appKey=? and (isValid=0 or isValid is null) \n" +
                    "ORDER BY downDate DESC \n" +
                    "";//--LIMIT 3
            List<String> listBacth=mySqlJdbcTemplate.queryForList(strSql,String.class,appKey);
            if (listBacth==null||listBacth.isEmpty()||listBacth.size()<3){

            }
            else{

                // 创建DataSourceTransactionManager
                DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(mySqlJdbcTemplate.getDataSource());

                // 创建TransactionTemplate
                TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);

                // 定义事务的内容
                transactionTemplate.execute((TransactionCallback<Void>) transactionStatus -> {
                    // 在这里执行数据库操作
                    //mySqlJdbcTemplate.update("INSERT INTO your_table (column1, column2) VALUES (?, ?)", value1, value2);
                    //mySqlJdbcTemplate.update("UPDATE your_table SET column1 = ? WHERE id = ?", newValue, id);


                    try {


                        for (int i = 1; i < listBacth.size(); i++) {
                            String strSqlTmp = "select main_id from " + mainDBModel.getMainTableName() + " where downBatchId=?";
                            List<Long> listMain_id = mySqlJdbcTemplate.queryForList(strSqlTmp, Long.class, listBacth.get(i));
                            if (listMain_id == null||listMain_id.size()<1) {


                                //for (int j = 0; j < mainDBModel.getListDetails().size(); j++) {
                                 //   strSqlTmp = "delete from " + mainDBModel.getListDetails().get(j).getDetailTableName() + " where main_id=?";
                                //    mySqlJdbcTemplate.update(strSqlTmp, main_id);
                               // }
                                //strSqlTmp = "delete from " + mainDBModel.getMainTableName() + " where main_id=?";
                                //mySqlJdbcTemplate.update(strSqlTmp, main_id);
                            }
                            else{
                                for (Long main_id :listMain_id){

                                    for (int j = 0; j < mainDBModel.getListDetails().size(); j++) {
                                        strSqlTmp = "delete from " + mainDBModel.getListDetails().get(j).getDetailTableName() + " where main_id=?";
                                        mySqlJdbcTemplate.update(strSqlTmp, main_id);
                                    }
                                    strSqlTmp = "delete from " + mainDBModel.getMainTableName() + " where main_id=?";
                                    mySqlJdbcTemplate.update(strSqlTmp, main_id);
                                }
                            }

                            strSqlTmp = "delete from qing_downdatabatch where appKey=? and downBatchId=?";
                            mySqlJdbcTemplate.update(strSqlTmp, appKey, listBacth.get(i));
                        }
                    }
                    catch (Exception e){
                        e.printStackTrace();
                        throw e;
                    }

                    // 如果需要回滚事务，可以在这里抛出异常
                    // 如果方法正常结束，事务将被提交
                    return null;
                });
            }
            //endregion


            bSuccess=true;

        }
        catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
        }


        return bSuccess;
    }

    private void DealAppDownData(String downBatchId,List<QingDownDataRowDataBase>  result) throws Exception{
        List<QingDownDataRowDataBase> listRows=result;
        try {


            if (listRows == null || listRows.isEmpty()) {

            } else {
                for (int i = 0; i < listRows.size(); i++) {
                    QingDownDataRowDataBase rowDataBase = listRows.get(i);
                    //获取行Id

                    mainDBModel.setApplyId(rowDataBase.getApplyId());
                    mainDBModel.setDownBatchId(downBatchId);

                    //每个字段去赋值
                    if (rowDataBase.getAnswers() == null || rowDataBase.getAnswers().isEmpty()) {

                    } else {
                        List<QingDownDataItemBase> listFields = rowDataBase.getAnswers();
                        for (int j = 0; j < listFields.size(); j++) {
                            QingDownDataItemBase itemBase = listFields.get(j);

                            if (itemBase.getValues() == null || itemBase.getValues().isEmpty()) {

                            } else {
                                //region 保存主表内容
                                try {
                                    if (itemBase.getValues() == null || itemBase.getValues().isEmpty()) {
                                        mainDBModel.PutFieldValue(itemBase.getQueTitle(), null);
                                    } else {
                                        List<QingDownDataItemValueBase> listFieldValues = itemBase.getValues();
                                        mainDBModel.PutFieldValue(itemBase.getQueTitle(),
                                                listFieldValues.get(0).getValue());
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                //endregion
                            }

                            //判断有没有明细表
                            if (itemBase.getTableValues() == null || itemBase.getTableValues().length < 1) {
                                //没有明细表
                            } else {
                                //有明细表
                                //如何判断是哪个明细表？

                                //region 有明细表
                                String strQueTitle = itemBase.getQueTitle();
                                //if (mainDBModel.getMapFieldContrast())
                                //判断是否存在当前字段的明细表字义
                                if (mainDBModel.CheckExistsDetailQueTitle(strQueTitle)) {
                                    //如果包含，则要写数据

                                    for (int k = 0; k < itemBase.getTableValues().length; k++) {
                                        //每一个list就是一行
                                        List<QingDownDataItemTableRowValueBase> listDetailRowValues = itemBase.getTableValues()[k];

                                        if (listDetailRowValues == null || listDetailRowValues.isEmpty()) {

                                        } else {
                                            for (int l = 0; l < listDetailRowValues.size(); l++) {

                                                QingDownDataItemTableRowValueBase tableRowValueBase = listDetailRowValues.get(l);
                                                if (tableRowValueBase == null) {

                                                } else {

                                                    String strDetailQueTitle=tableRowValueBase.getQueTitle();
                                                    String strDetailFieldValue=tableRowValueBase.getValues().get(0).getValue();

                                                    mainDBModel.PutDetailFieldValue(k, strQueTitle, strDetailQueTitle,strDetailFieldValue);
                                                }

                                                //mainDBModel.PutDetailFieldValue(k,strQueTitle,listDetailRowValues.get(l).getValues().get(0).getValue());
                                            }
                                        }

                                    }


                                }
                                //endregion
                            }

                        }
                    }

                    //保存到数据库
                    mainDBModel.SaveToDB(mySqlJdbcTemplate);


                }

            }
        }
        catch (Exception e){

            e.printStackTrace();
            throw e;
        }
    }
}
